import models from '../../../models'
import bcrypt from 'bcrypt'

export default defineEventHandler(async (event: any) => {
  try {
    const body = await readBody(event)
    const { email, password } = body

    const user = await models.User.findOne({
      where: { email }
    })

    if (!user) {
      return { success: false, message: '用户不存在' }
    }

    const isPasswordValid = await bcrypt.compare(password, user.password)
    if (!isPasswordValid) {
      return { success: false, message: '密码错误' }
    }

    setCookie(event, 'auth_token', 'logged_in', {
      httpOnly: true,
      path: '/',
      maxAge: 60 * 60 * 24 * 7 // 7 days
    })

    return { success: true }
  } catch (error) {
    return { success: false, message: '登录失败' }
  }
}) 